<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">

          <a-col :md="4" :sm="8">
            <a-form-item label="套餐名称">
              <a-input placeholder="请输入套餐名称" v-model="queryParam.packageName"></a-input>
            </a-form-item>
          </a-col>

          <a-col :md="5" :sm="10">
            <a-form-item label="车辆类型">
              <a-select placeholder="请选择车辆类型" v-model="queryParam.monthlyTypeId"
                        :options="parkMonthCarTypes"></a-select>
            </a-form-item>
          </a-col>

          <a-col :md="5" :sm="10">
            <a-form-item label="过期类型">
              <a-select placeholder="请选择过期车辆类型" v-model="queryParam.overdueTypeId" :options="parkCarTypes"></a-select>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" style="margin-right: 10px" type="primary" icon="plus" v-has="'monthmeal:add'">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('月卡套餐信息')" v-has="'monthmeal:export'">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-has="'monthmeal:delete'">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-has="'monthmeal:edit'">编辑</a>
           <a-divider type="vertical"/>
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical"/>
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)" v-has="'monthmeal:delete'">
              <a>删除</a>
            </a-popconfirm>
        </span>
        <span slot="startEndDate" slot-scope="text">
              {{ text.allowHandleStarting===1? "开始":"" }}{{text.allowHandleOf===1 && text.allowHandleStarting===1?"、":""}}{{text.allowHandleOf===1? "截止":""}}
          </span>
      </a-table>
    </div>

    <!-- 表单区域 -->
    <monthlyPackageInfo-modal ref="modalForm" @ok="modalFormOk"></monthlyPackageInfo-modal>
    <monthlyPackageInfo-modal-detail ref="modalFormDetail"></monthlyPackageInfo-modal-detail>
  </a-card>
</template>

<script>
  import MonthlyPackageInfoModal from './modules/MonthlyPackageInfoModal'
  import MonthlyPackageInfoModalDetail from './modules/MonthlyPackageInfoModalDetail'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import {deleteAction, getAction, downFile, postAction} from '@/api/manage'
  import { getMonthlyParkInfoList } from '@api/api'
  import {filterObj} from '@/utils/util';

  export default {
    name: "MonthlyPackageInfoList",
    mixins: [JeecgListMixin],
    components: {
      MonthlyPackageInfoModal,
      MonthlyPackageInfoModalDetail
    },
    data() {
      return {
        description: '月卡车部门组织表管理页面',
        // 表头
        columns: [
          {
            title: '停车场名称',
            align: "center",
            // width: 150,
            dataIndex: 'parkName'
          },
          {
            title: '套餐名称',
            // width: 100,
            align: "center",
            dataIndex: 'packageName'
          },
          {
            // title: '月租车辆类型名称',
            title: '车辆类型',
            // width: 100,
            align: "center",
            dataIndex: 'monthlyTypeName'
          },
          {
            title: '可绑定车位数',
            align: "center",
            // width: 80,
            dataIndex: 'bindingSpaceNumber'
          },
          {
            title: '可绑定车牌数',
            align: "center",
            // width: 80,
            dataIndex: 'bindingCarNumber'
          },
          {
            title: '周期单位',
            // width: 80,
            align: "center",
            dataIndex: 'cycleLength',
            customRender: function (t, r, index) {
              if (t === 1) {
                return "1天"
              }
              if (t === 2) {
                return "1月"
              }
            }
          },
          {
            title: '收费金额(元)',
            // width: 100,
            align: "center",
            dataIndex: 'charges',
            customRender: function (t, r, index) {
              return parseFloat((t / 100)).toFixed(2);
            }
          },
          {
            title: '满位处理方式',
            // width: 100,
            align: "center",
            dataIndex: 'fullManageName'
          },
          {
            title: '过期车辆类型',
            // width: 100,
            align: "center",
            dataIndex: 'overdueTypeName'
          },
          {
            title: '过期延期方式',
            // width: 100,
            align: "center",
            dataIndex: 'overdueDelayWay',
            customRender: function (t, r, index) {
              if (t === 1) {
                return "顺延"
              }
              if (t === 2) {
                return "跳延"
              }
            }
          },
          {
            title: '图片地址',
            // width: 100,
            align: "center",
            dataIndex: 'imageUrl',
            customRender: (r, row, index) => {
              // let r = record
              return (
                < img
              style = "max-width:35px;max-height:35px;min-height:20px;min-width:20px;text-align:center;cursor:pointer;border:1px #BFBFBF solid;padding: 2px 2px 2px 2px;background-color:white;"
              preview = {r}
              src = {r}
                > < /img>
              )
            },
          },
          {
            title: '允许办理起始截至日期',
            scopedSlots: {customRender: 'startEndDate'},
            // width: 100,
            align: 'center'
          },
          {
            title: '最大购买周期数',
            // width: 80,
            align: "center",
            dataIndex: 'maxCycle'
          },
          {
            title: '操作',
            dataIndex: 'action',
            // width: 120,
            align: "center",
            scopedSlots: {customRender: 'action'},
          }
        ],
        url: {
          list: "/monthlyPackageInfo/list",
          delete: "/monthlyPackageInfo/delete",
          deleteBatch: "/monthlyPackageInfo/deleteBatch",
          exportXlsUrl: "/monthlyPackageInfo/exportXls",
          importExcelUrl: "/monthlyPackageInfo/importExcel",
          getParkInfos: "/parking/parkInfo/parkInfoList",
          getParkMonthCarTypes: "/ConfigCarType/configCarType/parkMonthlyCarTypeList",
          getParkCarTypes: "/ConfigCarType/configCarType/parkCarTypeList"
        },
        queryParam: {
          'monthlyTypeId': '',
          'overdueTypeId': '',
          "packageName": '',
          "opTime_begin": "",
          "opTime_end": "",
          "type": "-1",

        },
        isorter: {
          column: 'createTime',
          order: 'desc',
        },
        parkInfos: [{label: '请选择车场', value: ''}],
        parkCarTypes: [{label: '请选择过期车辆类型', value: ''}],
        parkMonthCarTypes: [{label: '请选择车辆类型', value: ''}],
      }
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    created() {
      this.keyupEnter()
      this.loadParkInfo();
      this.loadParkCarTypes();
      this.loadParkMonthCarTypes();
    },
    methods: {
      parkInfoSelect() {
        this.loadParkCarTypes();
        this.loadParkMonthCarTypes();
        this.queryParam.monthlyTypeId = ''
        this.queryParam.overdueTypeId = ''
      },
      loadParkInfo() {
        const that = this
        getMonthlyParkInfoList().then((res) => {
          if (res.success) {
            if (res.result) {
              that.parkInfos = [{label: '请选择车场', value: ''}]
              res.result.forEach(parkInfo => {
                that.parkInfos.push({
                  label: parkInfo.parkName,
                  value: parkInfo.parkCode
                })
              })
            }
          }
        })
      },
      loadParkMonthCarTypes() {
        const that = this
        getAction(this.url.getParkMonthCarTypes).then((res) => {
          if (res.success) {
            if (res.result) {
              that.parkMonthCarTypes = [{label: '请选择车辆类型', value: ''}]
              res.result.forEach(parkCarTypes => {
                that.parkMonthCarTypes.push({
                  label: parkCarTypes.carTypeName,
                  value: parkCarTypes.id
                })
              })
            }
          }
        })
      },
      loadParkCarTypes() {
        const that = this
        postAction(this.url.getParkCarTypes, {parkCode: this.queryParam.parkCode}).then((res) => {
          if (res.success) {
            if (res.result) {
              that.parkCarTypes = [{label: '请选择过期车辆类型', value: ''},{label: "按车辆性质入场", value: "0"}]
              res.result.forEach(parkCarTypes => {
                that.parkCarTypes.push({
                  label: parkCarTypes.carTypeName,
                  value: parkCarTypes.id
                })
              })
            }
          }
        })
      },
      handleEdit(record) {
        this.$refs.modalForm.title = "编辑";
        this.$refs.modalForm.edit(record);
      },
      handleDetail(record) {
        this.$refs.modalFormDetail.title = "详情";
        this.$refs.modalFormDetail.edit(record);
      },
      handleExportXls(fileName) {
        let date = new Date()
        let dateStr = date.getFullYear() + "-" + Number(date.getMonth() + 1) + "-" + date.getDate()
        fileName = dateStr + fileName;
        let param = {...this.queryParam};
        downFile(this.url.exportXlsUrl, param).then((data) => {
          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        })
      },
      onChangeStartTime(date, dateString) {
        this.queryParam.opTime_begin = dateString;
      },
      onChangeEndTime(date, dateString) {
        this.queryParam.opTime_end = dateString;
      },
      searchQuery() {
        let startTime = this.queryParam.opTime_begin;
        let endTime = this.queryParam.opTime_end;
        if (startTime != "" && endTime != "") {
          if (startTime > endTime) {
            this.$message.error("开始时间不能大于结束时间");
            return
          }
        }
        if (startTime == "" && endTime != "") {
          this.$message.error("请选择开始时间");
          return
        }
        if (startTime != "" && endTime == "") {
          this.$message.error("请选择结束时间");
          return
        }
        this.loadData(1);
      },
      getQueryParams() {
        var param = Object.assign({}, this.isorter, this.queryParam);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        if (this.queryParam.opTime_begin != "" && this.queryParam.opTime_end != "") {
          param.opTime_begin = this.queryParam.opTime_begin + " 00:00:00";
          param.opTime_end = this.queryParam.opTime_end + " 23:59:59";
        }
        return filterObj(param);
      },

      loadData(arg) {
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records;
            this.ipagination.total = res.result.total;
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false;
        })
      },

      batchDel: function () {
        if (!this.url.deleteBatch) {
          this.$message.error("请设置url.deleteBatch属性!")
          return
        }
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        } else {
          var ids = "";
          for (var a = 0; a < this.selectionRows.length; a++) {
            ids += this.selectionRows[a].id + ",";
          }
          var that = this;
          this.$confirm({
            title: "确认删除",
            content: "是否删除选中数据?",
            onOk: function () {
              deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
                if (res.success) {
                  that.$message.success(res.message);
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.message);
                }
              });
            }
          });
        }
      },
      handleDelete: function (invateuserdetailId) {
        if (!this.url.delete) {
          this.$message.error("请设置url.delete属性!")
          return
        }
        var that = this;
        deleteAction(that.url.delete, {id: invateuserdetailId}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.loadData();
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      keyupEnter() {
        document.onkeydown = e => {
          let body = document.getElementsByTagName('body')[0]
          if (e.keyCode === 13) {
            this.loadData(1);
          }
        }
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>
